package com.sharer.last.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.sharer.last.base.enums.ExceptionCode;
import com.sharer.last.base.exception.BusinessException;
import com.sharer.last.base.utils.StringUtil;
import com.sharer.last.config.properties.OSSProperties;
import com.sharer.last.service.OssFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件注释地方
 *
 * @ClassName OssFileServiceImpl
 * @Author wangjin
 * @Date 2023/07/10/15:25
 * @Description
 * @Version 1.0
 */
@Service
@Slf4j
public class OssFileServiceImpl implements OssFileService {

    @Resource
    OSSProperties ossProperties;

    /**
     * 阿里云OSS文件上传
     *
     * @param file
     */
    @Override
    public String upload(MultipartFile file) {

        //获取相关配置
        String bucketName      = ossProperties.getBucketName();
        String endPoint        = ossProperties.getEndPoint();
        String accessKeyId     = ossProperties.getAccessKeyId();
        String accessKeySecret = ossProperties.getAccessKeySecret();

        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        //获取原生文件名
        String originalFilename = file.getOriginalFilename();
        //JDK8的日期格式
        LocalDateTime     time = LocalDateTime.now();
        DateTimeFormatter dft  = DateTimeFormatter.ofPattern("yyyyMMdd");

        //拼装OSS上存储的路径
        String folder    = dft.format(time);
        String fileName  = generateUUID();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

        //在OSS上bucket下的文件名
        String uploadFileName = "webimg/" + folder + "/" + fileName + extension;

        try {
            PutObjectResult result = ossClient.putObject(bucketName, uploadFileName, file.getInputStream());
            //拼装返回路径
            if (result != null) {
                return "https://" + bucketName + "." + endPoint + "/" + uploadFileName;
            }
        } catch (IOException e) {
            log.error("文件上传失败:{}", e.getMessage());
            throw new BusinessException(ExceptionCode.ERROR);
        } finally {
            //OSS关闭服务，不然会造成OOM
            ossClient.shutdown();
        }
        throw new BusinessException(ExceptionCode.ERROR);
    }

    /**
     * 阿里云文件上传
     *
     * @param url 网络url
     * @return
     */
    @Override
    public String upload(String url, String suffix) {

        //获取相关配置
        String bucketName      = ossProperties.getBucketName();
        String endPoint        = ossProperties.getEndPoint();
        String accessKeyId     = ossProperties.getAccessKeyId();
        String accessKeySecret = ossProperties.getAccessKeySecret();
        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        //JDK8的日期格式
        LocalDateTime     time = LocalDateTime.now();
        DateTimeFormatter dft  = DateTimeFormatter.ofPattern("yyyyMMdd");

        //拼装OSS上存储的路径
        String folder   = dft.format(time);
        String fileName = generateUUID();
        //获取原生文件名
        String extension = StringUtil.isNotBlank(suffix) ? suffix : url.substring(url.lastIndexOf("."));

        //在OSS上bucket下的文件名
        String uploadFileName = "webimg/" + folder + "/" + fileName + extension;
        try {
            InputStream     in     = getInputStreamByUrl(url);
            PutObjectResult result = ossClient.putObject(bucketName, uploadFileName, in);
            //拼装返回路径
            if (result != null) {
                return "https://" + bucketName + "." + endPoint + "/" + uploadFileName;
            }
        } catch (Exception e) {
            log.error("文件上传失败:{}", e.getMessage());
            throw new BusinessException(ExceptionCode.ERROR);
        } finally {
            //OSS关闭服务，不然会造成OOM
            ossClient.shutdown();
        }
        throw new BusinessException(ExceptionCode.ERROR);
    }

    /**
     * 获取随机字符串
     *
     * @return
     */
    private String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }


    /**
     * 从网络Url中下载文件
     *
     * @param uploadUrl
     * @throws IOException
     */
    public static InputStream downLoadByUrl(String uploadUrl) throws IOException {
        URL               url  = new URL(uploadUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(5 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        return conn.getInputStream();
    }

    public static InputStream getInputStreamByUrl(String strUrl) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20000);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(), output);
            ByteArrayInputStream var4 = new ByteArrayInputStream(output.toByteArray());
            return var4;
        } catch (Exception var14) {
            log.error(var14 + "");
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception var13) {
                log.error(var13 + "");
            }

        }

        return null;
    }
}
